import blockConfig from 'blockConfig'
import { promiseSpriteFrame } from 'imageWrapper'
import { pointToTiledPosition, poinToGrid } from 'positionWrapper'
import { BLOCK_TYPE, EDITOR_STATE, } from 'constant'

cc.Class({
    extends: cc.Component,

    properties: {
        mapBlock: cc.Prefab
    },

    onLoad() {
        let scene = cc.director.getScene()
        this.canvas = scene.getChildByName('Canvas')
        this.sideBar = this.canvas.getChildByName('sideBar')
        // this.currentState = this.sideBar.getChildByName('currentState')
        this.mapBoxListener = this.canvas.getChildByName('mapBox').getChildByName('mask').getChildByName('touchLayer') // 这个节点监听编辑状态下点到的点
        this.mapBlockLayer = this.canvas.getChildByName('mapBox').getChildByName('mapLayer').getChildByName('blockLayer')
        this.mainMapData = this.node.getComponent('mapData')

        this.editorState = EDITOR_STATE.COMMON_STATE // 编辑器状态
        this.willAddBlockId = 0 // 当前准备添加到地图的块的id
        this.selectingBlockId = 0 // 在地图上被选中的块的id
        this.stateDesc = null // 当前编辑状态的描述

        this.choosingScrollItem = null // 当前选中的 scroll 中的 item

        this.choosingBlock = null // 当前被选中的块

        this.isDraggingCreate = false

        this.mapBoxListener.on(cc.Node.EventType.TOUCH_START, this.onTouchMapBox, this)
        this.mapBoxListener.on(cc.Node.EventType.TOUCH_MOVE, this.dragOnEditor, this)
        this.mapBoxListener.on(cc.Node.EventType.TOUCH_END, this.clearDragState, this)
        this.mapBoxListener.on(cc.Node.EventType.TOUCH_CANCEL, this.clearDragState, this)

    },

    start() {

    },

    // scrollItem上的点击事件
    scrollItemTouchEvent(e) {
        let selectId = e.target.selectId
        let itemNode = e.target
        this.mapBoxListener.active = true

        this.clearChooseState()

        if (this.choosingScrollItem) {
            this.choosingScrollItem.color = cc.color(255, 255, 255, 255)
            this.choosingScrollItem.children[0].color = cc.color(255, 255, 255, 255)
        }
        if (this.choosingScrollItem == itemNode) {
            this.choosingScrollItem = null
            this.clearEditorState()
        } else {
            this.choosingScrollItem = itemNode
            itemNode.color = cc.color(60, 60, 60, 255)
            itemNode.children[0].color = cc.color(60, 60, 60, 255)
        }
        // console.log(selectId)
        // promiseSpriteFrame(url, imageNode)
        this.willAddBlockId = selectId
        this.editorState = EDITOR_STATE.READY_ADD_BLOCK

    },

    // 点击到地图监听器上面
    onTouchMapBox(e) {
        if (this.editorState === EDITOR_STATE.READY_ADD_BLOCK) {
            this.isDraggingCreate = true

            let worldPosition = e.touch._point
            let localPosition = this.mapBlockLayer.convertToNodeSpaceAR(worldPosition)
            let config = blockConfig[this.willAddBlockId]

            let isExistPlayer = this.checkMapExistPlayer()
            if (config.type == BLOCK_TYPE.CHARACTER && isExistPlayer) {
                console.log('只能有一个 player')
                return
            }
            // 先检查该位置有没有块，有就把原来该位置上的删除 TODO:
            let blockPosition = pointToTiledPosition(localPosition)
            let blockIndex = this.checkPositionExistBlock(blockPosition)
            if (blockIndex !== null) {
                this.deleteBlock(blockIndex)
            }

            let block = this.createBlockOnView(config, blockPosition)
            block.selectId = this.mainMapData.mapData.blocks.length

            // FIXME: 地图块要加属性的话需要改这里
            let dataItem = {
                position: blockPosition,
                type: config.type,
                path: config.path,
                width: config.width,
                height: config.height,

                blockId: config.id, // 这样命名是为了不和节点本身的属性命名冲突
                blockName: config.name,
                blockComponents: config.components || [],
            }

            this.mainMapData.mapData.blocks.push(dataItem)
        }
    },

    // 在地图上创建一个块 FIXME: 地图块要加属性的话需要改这里
    createBlockOnView(config, position) {
        let imageUrl = config.path
        let block = cc.instantiate(this.mapBlock)
        // if (position) {
        //     let grid = poinToGrid(position)
        //     let nodeName = grid.x + '_' + grid.y
        // }

        block.parent = this.mapBlockLayer
        block.blockType = config.type
        block.width = config.width || 100
        block.height = config.height || 100
        block.angle = config.angle || 0

        block.blockId = config.id // 这样命名是为了不和节点本身的属性命名冲突
        block.blockName = config.name
        block.blockComponents = config.components || []

        promiseSpriteFrame(imageUrl, block)

        // block.on(cc.Node.EventType.TOUCH_START, this.selectMapBlock, this)
        // block.on(cc.Node.EventType.TOUCH_MOVE, this.dragBlock, this)
        // block.on(cc.Node.EventType.TOUCH_END, this.resetDragState, this)
        // block.on(cc.Node.EventType.TOUCH_CANCEL, this.resetDragState, this)

        if (position) {
            block.setPosition(position)
        } else {
            block.setPosition(config.position)
        }
        return block
    },

    // 根据 id 删除块  这里是删除一个数据，然后清空画面再根据数据重新渲染
    deleteBlock(id) {
        this.mainMapData.mapData.blocks.splice(id, 1)

        this.clearBlocksView()
        this.renderBlocksMap()
    },

    // 检查地图中是否已经存在player
    checkMapExistPlayer() {
        let isExist = false
        let mapData = this.mainMapData.mapData.blocks
        for (let i = 0; i < mapData.length; i++) {
            if (mapData[i].type == BLOCK_TYPE.CHARACTER) {
                isExist = true
                break
            }
        }
        return isExist
    },

    // 检查相同位置是否有地图块，有的话返回地图块的 index
    checkPositionExistBlock(position) {
        let blocks = this.mainMapData.mapData.blocks
        for (let i = 0; i < blocks.length; i++) {
            let blockPosition = blocks[i].position
            if (blockPosition.x === position.x && blockPosition.y === position.y) {
                return i
            }
        }
        return null
    },

    // 根据地图块的数据渲染地图
    renderBlocksMap() {
        let mapData = this.mainMapData.mapData.blocks
        for (let i = 0; i < mapData.length; i++) {
            let d = mapData[i]
            let block = this.createBlockOnView(d)
            block.selectId = i
        }
    },

    // 清除编辑器状态
    clearEditorState() {
        this.mapBoxListener.active = false
        this.editorState = EDITOR_STATE.COMMON_STATE
    },

    // 清除选择的块的选择状态
    clearChooseState() {
        if (this.choosingBlock) {
            this.choosingBlock.color = cc.color(255, 255, 255, 255)
        }
        this.choosingBlock = null
    },

    // 清除视图层上的块
    clearBlocksView() {
        this.mapBlockLayer.removeAllChildren()
    },

    // 清除块的数据
    clearBlocksData() {
        this.mainMapData.mapData.blocks = []
    },

    // 在编辑窗上移动
    dragOnEditor(e) {
        let worldPosition = e.touch._point
        let localPosition = this.mapBlockLayer.convertToNodeSpaceAR(worldPosition)
        let grid = poinToGrid(localPosition)
        let gridString = grid.x + '_' + grid.y
        // 这样可以减少拖动的计算，如果在同一格上移动就不增加新的块去覆盖了
        if (this.lastGrid == gridString) {
            return
        }
        this.lastGrid = gridString

        if (this.isDraggingCreate) {
            this.onTouchMapBox(e)
        }

    },

    // 清除拖动状态
    clearDragState() {
        this.isDraggingCreate = false
    },

    // update (dt) {},
});
